package spring.rest;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @author ZH
 */
@Lazy(false)
@Component
public class RestTemplateUtils {
    @Autowired
    private RestTemplate restTemplate;

    private static RestTemplateUtils restTemplateUtils;

    @PostConstruct
    public void init(){
        restTemplateUtils = this;
        restTemplateUtils.restTemplate = this.restTemplate;
    }

    /**
     * 解析Json
     * @param json Json String
     * @param pattern ex:data.accessToken 点取value
     * @return String value
     */
    public static String parseJson(String json,String pattern){
        String value = "";
        String[] list = pattern.split("\\.");
        JSONObject jsonObject = (JSONObject) JSONObject.parse(json);
        try {
            for (int i = 0; i < list.length; i++) {
                if (i != list.length - 1){
                    jsonObject = jsonObject.getJSONObject(list[i]);
                }else {
                    value = jsonObject.getString(list[i]);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }

    public static String getUrl(String url, Map<String,String> params) {
        return getUrl(url,params,null);
    }

    public static String getUrl(String url, Map<String,String> params,Map<String,String> headers) {
        if (params == null){
            params = new HashMap<>();
        }
        if (headers == null){
            headers = new HashMap<>();
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("timestamp", String.valueOf(System.currentTimeMillis()));
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpHeaders.add(entry.getKey(),entry.getValue());
        }
        HttpEntity<String> formEntity = new HttpEntity<String>(null,httpHeaders);
        StringBuilder queryString = new StringBuilder();
        if (params.entrySet().size() > 0){
            queryString.append("?");
        }
        Set<Map.Entry<String, String>> entries = params.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            queryString.append(entry.getKey()).append("={").append(entry.getKey()).append("}");
            if (iterator.hasNext()){
                queryString.append("&");
            }
        }
        System.out.println("queryString=" + queryString);

        ResponseEntity<String> exchange = restTemplateUtils.restTemplate.exchange(url + queryString, HttpMethod.GET, formEntity, String.class, params);
        return exchange.getBody();
    }


    public static String postUrl(String url, Map<String,String> params){
        return postUrl(url,params,null);
    }

    /**
     * params key：value形式
     * @param url
     * @param params
     * @param headers
     * @return json字符串
     */
    public static String postUrl(String url, Map<String,String> params,Map<String,String> headers){
        if (params == null){
            params = new HashMap<>();
        }
        if (headers == null){
            headers = new HashMap<>();
        }
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("api-version", "1.0");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            requestHeaders.add(entry.getKey(),entry.getValue());
        }

        //body
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            requestBody.add(entry.getKey(),entry.getValue());
        }
        //HttpEntity
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders);
        //post
        ResponseEntity<String> responseEntity = restTemplateUtils.restTemplate.postForEntity(url, requestEntity, String.class);
        return responseEntity.getBody();
    }
}
